const { isArray, isNumber } = require("lodash");

const ByteUtil = {
  getPileCode: (cbuf) => {
    const pbyte = [];
    for (let i = 0; i < 8; i++) {
      pbyte[i] = cbuf[i + 6];
    }
    return Buffer.from(pbyte).toString();
  },
  getPileInfo: (cbuf) => {
    let pile = {};
    let versonChar = ByteUtil.byteTo16(cbuf[15]).split('');
    pile.hardVer = versonChar[0] + '.' + (versonChar[1] || 0);
    versonChar = ByteUtil.byteTo16(cbuf[16]).split('');
    pile.softVer = versonChar[0] + '.' + (versonChar[1] || 0);
    versonChar = ByteUtil.byteTo16(cbuf[17]).split('');
    pile.bootVer = versonChar[0] + '.' + (versonChar[1] || 0);
    versonChar = ByteUtil.byteTo16(cbuf[18]).split('');
    pile.lcmVer = versonChar[0] + '.' + (versonChar[1] || 0);
    versonChar = ByteUtil.byteTo16(cbuf[19]).split('');
    pile.proVer = versonChar[0] + '.' + (versonChar[1] || 0);
    pile.spotType = cbuf[20] & 0xFF;
    return pile;
  },
  byteTo16: (by) => {
    return (by & 0xFF).toString(16);
  },
  analysisDataIndex: (res, i) => {
    return (res[i] & 0xFF) | ((res[i + 1] << 8) & 0xFF00);
  },
  getByteByStx: (cmd, index, by) => {
    const rnd = Math.floor(Math.random() * 250);
    by[0] = 2;
    by[1] = 0;
    by[2] = index & 0xFF;
    by[3] = (index & 0xFF00) >> 8;
    by[4] = 0xFF & rnd;
    by[5] = 0xFF & cmd;
    return by;
  },
  getByteByPileCodeOrAccountNo: (start, context, by) => {
    const bytes = Buffer.from(context);
    for (let i = 0; i < bytes.length; i++) {
      by[i + start] = bytes[i];
    }
    return by;
  },
  getPrice: (start, price, by) => {
    const totalPrice = parseFloat(price) * 100;
    by[start] = (totalPrice >>> 0) & 0xFF;
    by[start + 1] = (totalPrice >>> 8) & 0xFF;
    return by;
  },
  getByFee: (by, fees, service) => {
    // 服务费
    by = ByteUtil.getPrice(86, service, by);
    if (!isArray(fees)) {
      by[14] = 0;
      by = ByteUtil.getPrice(15, fees, by);
    } else {
      by[14] = 1;
      let rateNum = 0;
      for (let i = 0; i < fees.length; i++) {
          const feeDetail = fees[i];
          rateNum++;
          const beginHour = parseInt(feeDetail.beginHour);
          const endHour = parseInt(feeDetail.endHour);
          for (let j = beginHour + 17; j < endHour + 17; j++) {
            by[j] = rateNum - 1 & 0xFF;
          }
          by = ByteUtil.getPrice(64 + rateNum * 2, feeDetail.price, by);
      }
      by[65] = rateNum & 0xFF;
    }
    return by;
  },
  getByteByExit: (by) => {
    let sum = 0;
    for (let j = 4; j < by.length - 2; j++) {
      sum += by[j] & 0xFF;
      by[j] = by[j] & 0xFF;
    }
    by[by.length - 2] = sum & 0xFF;
    by[by.length - 1] = 3;
    by[1] = by.length & 0xFF;
    return by;
  }
}
module.exports = ByteUtil;
